<template>
  <a-layout-header class="header">
    <a-menu v-model:selectedKeys="selectedKeys" theme="dark" mode="horizontal" style="width: 100%">
      <a-menu-item key="1">
        <router-link to="/">首页</router-link>
      </a-menu-item>
      <a-menu-item key="4">
        <router-link to="/about">关于我们</router-link>
      </a-menu-item>
      <a-menu-item key="2" v-if="user.id">
        <router-link to="/admin/ebook">电子书管理</router-link>
      </a-menu-item>
      <a-menu-item key="3" v-if="user.id">
        <router-link to="/admin/category">分类管理</router-link>
      </a-menu-item>
      <a-menu-item key="logout" v-if="user.id" @click="handleLogout">
        <a-avatar :src="user.avatar" />
        <span style="margin-left: 8px">登出</span>
      </a-menu-item>
      <div style="margin-left: auto">
        <a-menu-item key="login" v-if="!user.id" @click="showLoginModal">
          <span class="login-text">登录</span>
        </a-menu-item>
      </div>
    </a-menu>
  </a-layout-header>

  <a-modal v-model:visible="loginVisible" title="登录" @ok="handleLogin" :footer="null">
    <a-form :model="loginForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-form-item label="用户名">
        <a-input v-model:value="loginForm.loginName" />
      </a-form-item>
      <a-form-item label="密码">
        <a-input-password v-model:value="loginForm.password" />
      </a-form-item>
      <a-form-item :wrapper-col="{ span: 18, offset: 6 }">
        <a-button type="primary" @click="handleLogin" block>登录</a-button>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue';
import { useRoute } from 'vue-router';
import axios from 'axios';
import router from "@/router";
const showAdminMenus = computed(() => user.value.id !== null);
const showLoginUser = computed(() => user.value.id !== null);
const selectedKeys = ref<string[]>([]);
const route = useRoute();
const user = ref({
  id: null,
  name: '',
  avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png',
});
const loginVisible = ref(false);
const loginForm = ref({
  loginName: '',
  password: '',
});

const updateSelectedKeys = () => {
  selectedKeys.value = [route.path.split('/')[1] || '1'];
};

onMounted(() => {
  updateSelectedKeys();
  const token = localStorage.getItem('token');
  if (token) {
    axios.get('/user/info', { headers: { Authorization: token } })
        .then(response => {
          if (response.data.success) {
            user.value = response.data.content;
          } else {
            localStorage.removeItem('token');
          }
        })
        .catch(() => localStorage.removeItem('token'));
  }
});

watch(route, updateSelectedKeys);

const showLoginModal = () => {
  loginVisible.value = true;
};

const handleLogin = async () => {
  try {
    const response = await axios.post('/user/login', loginForm.value);
    if (response.data.success) {
      user.value = response.data.content;
      loginVisible.value = false;
      localStorage.setItem('token', user.value.token);
      loginForm.value = { loginName: '', password: '' };
    } else {
      alert(response.data.message);
    }
  } catch (error) {
    console.error('Login error:', error);
  }
};

const handleLogout = async () => {
  const token = localStorage.getItem('token');
  if (token) {
    try {
      await axios.get('/user/logout', { headers: { Authorization: token } });
      user.value = { id: null, name: '', avatar: '' };
      localStorage.removeItem('token');
      router.push('/');
    } catch (error) {
      console.error('Logout error:', error);
      alert('Logout failed. Please try again.');
    }
  }
};
</script>

<style scoped>
@media (max-width: 768px) {
  .ant-menu-horizontal {
    display: flex;
    flex-direction: row;
    min-width: 100%;
    flex-wrap: nowrap;
  }
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 64px;
  padding: 0 20px;
  color: rgba(255, 255, 255, 0.65);
  background: #001529;
}

.logo {
  width: 80px;
  height: 31px;
  margin: 16px 16px 16px 0;
  background: rgba(255, 255, 255, 0.25);
}

.login-text {
  cursor: pointer;
}

.login-text:hover {
  color: #fff;
}
</style>
